package com.example.behaviour.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.behaviour.config.SpringUtils;
import com.example.behaviour.mapper.ApUserFriendRequestMapper;
import com.example.behaviour.mapper.ApUserMsgMapper;
import com.example.behaviour.mapper.ApUserRelationMapper;
import com.example.behaviour.message.AddFriendRequestMessage;
import com.example.behaviour.message.AddFriendResponseMessage;
import com.example.behaviour.pojos.ApUserFriendRequest;
import com.example.behaviour.pojos.ApUserMsg;
import com.example.behaviour.pojos.ApUserRelation;
import com.example.behaviour.session.SessionFactory;
import com.example.model.user.pojos.ApUser;
import io.goeasy.GoEasy;
import io.goeasy.publish.GoEasyError;
import io.goeasy.publish.PublishListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Slf4j
public class AddFriendRequestMessageHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    private ApUserRelationMapper apUserRelationMapper;

    @Autowired
    private ApUserFriendRequestMapper apUserFriendRequestMapper;

    @Autowired
    private ApUserMsgMapper apUserMsgMapper;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        apUserFriendRequestMapper = SpringUtils.getBean(ApUserFriendRequestMapper.class);
        apUserRelationMapper = SpringUtils.getBean(ApUserRelationMapper.class);
        apUserMsgMapper = SpringUtils.getBean(ApUserMsgMapper.class);

        JSONObject jsonObject = JSONObject.parseObject(msg.text());
        if(jsonObject.containsKey("refuse")){
            AddFriendRequestMessage addFriendRequestMessage = JSONObject.toJavaObject(jsonObject,AddFriendRequestMessage.class);

//

            ApUserRelation apUserRelation = new ApUserRelation();
            BeanUtils.copyProperties(addFriendRequestMessage,apUserRelation);
            apUserRelation.setCreatedTime(new Date());
//            apUserRelation.setUserId(addFriendRequestMessage.getFriendId());
//            apUserRelation.setFriendId(addFriendRequestMessage.getUserId());
//            apUserRelation.setFriendName(addFriendRequestMessage.getUserName());
//            apUserRelation.setUserName(addFriendRequestMessage.getFriendName());


            ApUserRelation other = new ApUserRelation();
            BeanUtils.copyProperties(apUserRelation,other);
            other.setUserName(apUserRelation.getFriendName());
            other.setUserId(apUserRelation.getFriendId());
            other.setFriendId(apUserRelation.getUserId());
            other.setFriendName(apUserRelation.getUserName());
            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("userId",apUserRelation.getUserId());
            queryWrapper2.eq("friendId",apUserRelation.getFriendId());
            ApUserRelation relation = apUserRelationMapper.selectOne(queryWrapper2);
            if("1".equals(jsonObject.get("refuse").toString()) && relation == null){
                apUserRelationMapper.insert(other);
                apUserRelationMapper.insert(apUserRelation);
            }


            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("friendId",addFriendRequestMessage.getUserId());
            queryWrapper.eq("userId",addFriendRequestMessage.getFriendId());
            queryWrapper.eq("addInfo",addFriendRequestMessage.getAddInfo());
            System.out.println("userId "+addFriendRequestMessage.getUserId());
            System.out.println("friendId "+addFriendRequestMessage.getFriendId());
            System.out.println("apUserRelation "+apUserRelation.toString());
            ApUserFriendRequest apUserFriendRequest = null;
            List<ApUserFriendRequest> apUserFriendRequestList = apUserFriendRequestMapper.selectList(queryWrapper);
            for (int i = 0;i < apUserFriendRequestList.size();i++){
                if(apUserFriendRequestList.get(i).getSuccess() == 0){
                    apUserFriendRequest = apUserFriendRequestList.get(i);
                    break;
                }
            }
            if("1".equals(jsonObject.get("refuse").toString())){
                apUserFriendRequest.setSuccess(1);
            }else{
                apUserFriendRequest.setSuccess(-1);
            }

            apUserFriendRequestMapper.updateById(apUserFriendRequest);



//            ApUser toUser = apUserMapper.selectById(apUserMsg.getUserId());



//            ChannelHandlerContext channel_user = SessionFactory.getSession().getChannel(addFriendRequestMessage.getUserName());
            ChannelHandlerContext channel_friend = SessionFactory.getSession().getChannel(addFriendRequestMessage.getFriendName());
            AddFriendResponseMessage addFriendResponseMessage1;
            if(apUserFriendRequest.getSuccess() == 1){
                addFriendResponseMessage1 = new AddFriendResponseMessage("好友添加成功");
            }else{
                addFriendResponseMessage1 = new AddFriendResponseMessage("您与拒绝添加好友");
            }

            AddFriendResponseMessage addFriendResponseMessage2;
            if(apUserFriendRequest.getSuccess() == 1){
                addFriendResponseMessage2 = new AddFriendResponseMessage("您的好友申请已通过");
                ApUserMsg apUserMsg = new ApUserMsg();
                apUserMsg.setFromUser(addFriendRequestMessage.getUserName());
                apUserMsg.setFromId(addFriendRequestMessage.getUserId());
                apUserMsg.setContent(apUserMsg.getFromUser()+"已通过您的好友申请");
                apUserMsg.setType(1);
                apUserMsg.setCreatedTime(new Date());
                apUserMsg.setUserId(addFriendRequestMessage.getFriendId());
                apUserMsg.setIsRead(0);
//            apUserMsg.setArticleId(comment.getArticleId());
                apUserMsgMapper.insert(apUserMsg);

                GoEasy goEasy = new GoEasy("https://rest-hz.goeasy.io", "BC-b6050660635342f89d6b38039bfa2af0");
                goEasy.publish(addFriendRequestMessage.getFriendName(), apUserMsg.getFromUser()+"已通过您的好友申请", new PublishListener(){
                    @Override
                    public void onSuccess() {
                        System.out.println("Publish success.");
                    }

                    @Override
                    public void onFailed(GoEasyError error) {
                        System.out.println("Failed to Publish message, error:" + error.getCode() + " , " + error.getContent());
                    }
                });
            }else{
                addFriendResponseMessage2 = new AddFriendResponseMessage("您的好友申请已被拒绝");
                ApUserMsg apUserMsg = new ApUserMsg();
                apUserMsg.setFromUser(addFriendRequestMessage.getUserName());
                apUserMsg.setFromId(addFriendRequestMessage.getUserId());
                apUserMsg.setContent(apUserMsg.getFromUser()+"已拒绝您的好友申请");
                apUserMsg.setType(1);
                apUserMsg.setCreatedTime(new Date());
                apUserMsg.setUserId(addFriendRequestMessage.getFriendId());
                apUserMsg.setIsRead(0);
//            apUserMsg.setArticleId(comment.getArticleId());
                apUserMsgMapper.insert(apUserMsg);

                GoEasy goEasy = new GoEasy("https://rest-hz.goeasy.io", "BC-b6050660635342f89d6b38039bfa2af0");
                goEasy.publish(addFriendRequestMessage.getFriendName(), apUserMsg.getFromUser()+"已拒绝您的好友申请", new PublishListener(){
                    @Override
                    public void onSuccess() {
                        System.out.println("Publish success.");
                    }

                    @Override
                    public void onFailed(GoEasyError error) {
                        System.out.println("Failed to Publish message, error:" + error.getCode() + " , " + error.getContent());
                    }
                });
            }



            TextWebSocketFrame frame1 = new TextWebSocketFrame(JSON.toJSONString(addFriendResponseMessage1));
            TextWebSocketFrame frame2 = new TextWebSocketFrame(JSON.toJSONString(addFriendResponseMessage2));
            frame2.retain();
            frame1.retain();

            ctx.writeAndFlush(frame1);
            if(channel_friend != null){
                log.info("channel_friend is null");
                channel_friend.writeAndFlush(frame2);
            }else{
                log.info("写入数据库");
            }

            return;
        }
        msg.retain();
        ctx.fireChannelRead(msg);
    }
}
